import {getImgCode, sendSignUpCode, bindPhone} from 'config/api'
import { Toast } from 'antd-mobile';
import {delay} from 'dva/saga'
import router from 'umi/router'
export default {
  namespace: 'login',
  state: {
    imgCodeSrc: '',
    disableGetPhoneCode: false,
    countTime: 60
  },
  reducers:{
    save(state, {payload}){
      return {...state, ...payload}
    }
  },
  effects: {
    *getImgCodeEff(action, {call,put}){
      let response = yield call(getImgCode)
			yield put({
        type: 'save',
        payload: {imgCodeSrc: response}
      })
    },
    *getPhoneCodeEff({PhoneNumbers, imgCode},{call, put}){
      let {code, msg} = yield call(sendSignUpCode, {PhoneNumbers, imgCode})
      if(code === 0){
        Toast.success(msg)
        yield put({
          type: 'disableCanGetPhoneCode'
        })
      }else{
        Toast.fail(msg)
      }
    },
    *disableCanGetPhoneCode(action,{call,put}){
      yield put({
        type: 'save',
        payload: {disableGetPhoneCode: true, countTime: 60}
      })
      let count = 60
      while(count > 0){
        yield call(delay, 1000)
        yield put({
          type: 'save',
          payload: {countTime: --count}
        })
      }
      yield put({
        type: 'save',
        payload: {disableGetPhoneCode: false, countTime: 0}
      })
    },
    *bindPhoneEff({signUpCode,PhoneNumbers},{call,put}){
      let {code, msg} = yield call(bindPhone,{signUpCode,PhoneNumbers})
      if(code === 0){
        Toast.success(msg)
        router.push('/?tabName=main')
      }else{
        Toast.fail(msg)
      }
    }
  }
}
